<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button type="primary" @click="handleAction('add','')">绑定新账号</el-button>
      </div>

      <el-table
        v-loading.fullscreen.lock="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @sort-change="handleSort"
      >
        <el-table-column align="center" label="ID" prop="id" sortable="custom" />
        <el-table-column align="center" prop="googlemerchantconfig__ads_id" label="广告" sortable="custom">
          <template slot-scope="scope">
            <span style="display: block">{{ scope.row.googlemerchantconfig__website__domain }}</span>
            <span>{{ scope.row.googlemerchantconfig__ads_id }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="下载文件" prop="file_url" sortable="custom">
          <template slot-scope="scope">
            <span style="display: block"><a :href="scope.row.file_url" target="_blank">下载</a></span>
            <span style="display: block">下载服务器:{{ scope.row.gsapi_ip }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型" prop="date_type" sortable="custom" />
        <el-table-column align="center" label="包含网站" prop="domains" sortable="custom" />
        <el-table-column align="center" label="备注" prop="note" sortable="custom" />
        <el-table-column align="center" label="同步日期" prop="update_at" sortable="custom" />
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleSync(scope.row)">更新</el-button>
            <el-button size="mini" type="warning" @click="handleAction('edit', scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
      <el-dialog
        append-to-body
        title="添加Google广告报告下载文件"
        :width="width"
        :visible.sync="innerDialogVisible"
        :close-on-click-modal="false"
      >
        <el-form :model="temp" label-position="left" label-width="120px">
          <el-form-item v-if="action !== 'delete'" label="file_url:">
            <el-input v-model="temp.file_url" />
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="备注:">
            <el-input v-model="temp.note" />
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="type:">
            <el-select v-model="temp.date_type" style="width: 100%" filterable clearable placeholder="类型">
              <el-option label="Yesterday" value="Yesterday" />
              <el-option label="Last 14 days" value="Last14days" />
              <el-option label="Last 7 days" value="Last7days" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="关联GMC">
            <el-select v-model="temp.googlemerchantconfig_id" style="width: 100%" filterable clearable placeholder="MC配置">
              <el-option v-for="item in this.merchentconfigs" :key="item.id" :label="item.website__domain" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="下载服务器">
            <el-autocomplete
              v-model="temp.gsapi_ip"
              :fetch-suggestions="querySearchServer"
              placeholder="请输入内容"
            /><span> PS:输入域名或者ip搜索</span>
          </el-form-item>
          <el-form-item label="port" f="action !== 'delete'">
            <el-input v-model="temp.gsapi_port" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="innerDialogVisible = false">取 消</el-button>
          <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, Sync } from '@/api/orders/googleadsreportconfig'
import { Get as GetServers } from '@/api/orders/serverstatus'
import { Get as GetConfigs } from '@/api/orders/merchantconfig'

import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Googleadsreportconfig',
  props: ['dVisible', 'googlemerchantconfig_id'],
  data() {
    return {
      processLoading: false,
      feedproductVisual: false,
      addfeedDialogVisual: false,
      syncloading: false,
      fetchloading: false,
      data: [],
      title: 'google广告每日报告',
      listLoading: true,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      temp: {
        note: '',
        date_type: 'Yesterday',
        file_url: 'export?format=xlsx',
        gsapi_ip: '',
        gsapi_port: 8000,
        googlemerchantconfig_id: ''
      },
      width: '',
      merchentconfigs: [],
      innerDialogVisible: false
    }
  },
  watch: {
    dVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.hanldleGetConfigs()
        this.getList()
      }
    },
    googlemerchantconfig_id(v) {
      this.temp.googlemerchantconfig_id = v
    }
  },
  methods: {
    querySearchServer(v, cb) {
      GetServers(null, qs.stringify({
        kw: v,
        pagesize: 10
      })).then(response => {
        const results = []
        for (let i = 0; i < response.data.data.length; i++) {
          results.push({ 'value': response.data.data[i]['gsapi_ip'] })
        }
        console.log(results)
        cb(results)
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        file_url: '',
        website_id: ''
      }
    },
    hanldleGetConfigs() {
      GetConfigs(null, null)
        .then(response => {
          this.merchentconfigs = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        website_id: this.website_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleSync(row) {
      this.listLoading = true
      Sync({
        id: row.id
      }
      ).then(response => {
        this.notify('处理成功')
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.googlemerchantconfig_id}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改站点${row.googlemerchantconfig_id}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'add':
          this.width = '50%'
          this.title = `添加新报告文件下载链接`
          this.temp.googlemerchantconfig_id = this.googlemerchantconfig_id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'add':
          this.listLoading = true
          Post({
            date_type: _data.date_type,
            file_url: _data.file_url,
            note: _data.note,
            gsapi_ip: _data.gsapi_ip,
            gsapi_port: _data.gsapi_port,
            googlemerchantconfig_id: _data.googlemerchantconfig_id
          }
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
            this.listLoading = false
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
        case 'delete' :
          this.listLoading = true
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
        case 'edit':
          this.listLoading = true
          Put(_data.id, {
            note: _data.note,
            date_type: _data.date_type,
            gsapi_ip: _data.gsapi_ip,
            gsapi_port: _data.gsapi_port,
            googlemerchantconfig_id: _data.googlemerchantconfig_id,
            file_url: _data.file_url
          }).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-input {
    width: auto;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 5px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 5px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 10px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 60px;
    padding-top: 5px;
  }

  .top >>> .el-select {
    width: 300px;
  }

</style>
